﻿using Dt261.db;
using Dt261.help;
using Dt261.Model;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Dt261.ViewModel
{
    public class TestResult
    {
        public string Left { get; set; }

        public string Right { get; set; }

        public string CenterB { get; set; }

        public string LeftB { get; set; }

        public string RightB { get; set; }

        public string Center { get; set; }

    }
    class PreviewPageViewModel:GalaSoft.MvvmLight.ViewModelBase
    {
        public delegate void selectPureToneResultchanged(Dictionary<int, TestItem> list, bool isright,int mmtype=0,int needline = 0);
        //定义一个事件
        public event selectPureToneResultchanged SelectPureToneResultEvent;

        public delegate void selectTabChanged(int selectIndex = 0);
        //定义一个事件
        public event selectTabChanged SelecTabEvent;


        PureToneResultDb resultDB;
        private PureToneResult selectPureToneResult;
        private MemberInfo selectMember;

        private int currentIndex;

        private string titleText;

        private string left_ac;
        private string right_ac;
        private string left_ac_mask;
        private string right_ac_mask;

        private string left_bc;
        private string right_bc;
        private string left_bc_mask;
        private string right_bc_mask;

        private string left_ff;
        private string right_ff;
        private string left_ff_mask;
        private string right_ff_mask;

        public string Left_ac { get => left_ac; set => left_ac = value; }
        public string Right_ac { get => right_ac; set => right_ac = value; }
        public string Left_ac_mask { get => left_ac_mask; set => left_ac_mask = value; }
        public string Right_ac_mask { get => right_ac_mask; set => right_ac_mask = value; }
        public string Left_bc { get => left_bc; set => left_bc = value; }
        public string Right_bc { get => right_bc; set => right_bc = value; }
        public string Left_bc_mask { get => left_bc_mask; set => left_bc_mask = value; }
        public string Right_bc_mask { get => right_bc_mask; set => right_bc_mask = value; }
        public string Left_ff { get => left_ff; set => left_ff = value; }
        public string Right_ff { get => right_ff; set => right_ff = value; }
        public string Left_ff_mask { get => left_ff_mask; set => left_ff_mask = value; }
        public string Right_ff_mask { get => right_ff_mask; set => right_ff_mask = value; }
        public int CurrentIndex { get => currentIndex; set {
                currentIndex = value;
                if (SelecTabEvent != null)
                    SelecTabEvent(currentIndex);
            }
        }

        private ObservableCollection<TestResult> results;
        public ObservableCollection<TestResult> Results { get => results; set { results = value; RaisePropertyChanged(); } }


        private string ac_low;
        private string bc_low;

        private string ac_high;
        private string bc_high;

        public string Ac_low { get => ac_low; set { ac_low = value; RaisePropertyChanged(); } }

        public string Bc_low { get => bc_low; set { bc_low = value; RaisePropertyChanged(); } }
        public string Ac_high { get => ac_high; set { ac_high = value; RaisePropertyChanged(); } }

        public string Bc_high { get => bc_high; set { bc_high = value; RaisePropertyChanged(); } }


        public PureToneResult SelectPureToneResult
        {
            get => selectPureToneResult;
            set
            {

                selectPureToneResult = value;
                if (SelectPureToneResultEvent != null)
                {
                    SelectPureToneResultEvent(null, true);
                    SelectPureToneResultEvent(null, false);
                    if (value != null)
                    {

                        resultDB.GetChildrenByUid(value);

                        Results = new ObservableCollection<TestResult>();
                     
                        


                        int leftac = 0;
                        int rightac = 0;
                        int centerac = 0;
                        int leftbc = 0;
                        int rightbc = 0;
                        int centerbc = 0;

                        int leftacCount = 0;
                        int rightacCount = 0;
                       
                        int leftbcCount = 0;
                        int rightbcCount = 0;


                        List<ResultEntry> aclow = new List<ResultEntry>();
                        List<ResultEntry> achigh = new List<ResultEntry>();
                        List<ResultEntry> bclow = new List<ResultEntry>();
                        List<ResultEntry> bchigh = new List<ResultEntry>();

                        foreach (ResultDataSet s in selectPureToneResult.DataSets)
                        {

                            int sum = 0;
                            int count = 0;

                            List<ResultEntry> low = s.HeadsetMode == 1 ? bclow : aclow;
                            List<ResultEntry> high = s.HeadsetMode == 1 ? bchigh : achigh;


                            foreach (ResultEntry entry in s.Entrys)
                            {

                                if(entry.ValueX == 500 || entry.ValueX == 1000|| entry.ValueX == 2000)
                                {
                                    low.Add(entry);
                                }
                                else if (entry.ValueX == 3000 || entry.ValueX == 4000 || entry.ValueX == 6000)
                                {
                                    high.Add(entry);
                                }

                                sum += entry.ValueY;
                                count++;
                            }


                        
                            if (s.IsRight == 1 && s.HeadsetMode == 1)
                            {
                                    if (count > 0)
                                        //右耳骨导
                                        rightbc = sum / count;
                                rightbcCount = count;
                            }
                            else if (s.IsRight == 1 && s.HeadsetMode == 0)
                            {
                                if (count > 0)
                                    //右耳气导
                                    rightac = sum / count;
                                rightacCount = count;
                            }
                            else if (s.IsRight == 0 && s.HeadsetMode == 1)
                            {
                                if (count > 0)
                                    //右耳气导
                                    leftbc = sum / count;
                                leftbcCount = count;
                            }
                            else
                            {
                                if (count > 0)
                                    //右耳气导
                                    leftac = sum / count;
                                leftacCount = count;
                            }
                        }

                        if (leftacCount + rightacCount > 0)
                        centerac = (leftac* leftacCount + rightac* rightacCount) /( leftacCount+ rightacCount);

                        if (leftbcCount + rightbcCount > 0)
                            centerbc = (leftbc * leftbcCount + rightbc * rightbcCount) / (leftbcCount + rightbcCount);


                        Results.Add(new TestResult() { Left = leftac==0?"未测试":""+ leftac,
                            Right = rightac == 0 ? "未测试" : "" + rightac,
                            Center = centerac == 0 ? "未测试" : "" + centerac,
                            LeftB = leftbc == 0 ? "未测试" : "" + leftbc,
                            RightB = rightbc == 0 ? "未测试" : "" + rightbc,
                            CenterB = centerbc == 0 ? "未测试" : "" + centerbc
                        });

//                        双耳语频就是指的 500，1000，2000这三个频率的平均值
//双耳高频就是指的 3000，4000，6000这三个频率的平均值
                        Ac_low = "";
                        if (aclow.Count ==6)
                        {
                            int sum = 0;
                            foreach (ResultEntry s in aclow)
                            {
                                sum += s.ValueY;
                            }
                            Ac_low += sum / 6;
                        }



                        Bc_low = "";
                        if (bclow.Count == 6)
                        {
                            int sum = 0;
                            foreach (ResultEntry s in bclow)
                            {
                                sum += s.ValueY;
                            }
                            Bc_low += sum / 6;
                        }

                        Ac_high = "";
                        if (achigh.Count == 6)
                        {
                            int sum = 0;
                            foreach (ResultEntry s in achigh)
                            {
                                sum += s.ValueY;
                            }
                            Ac_high += sum / 6;
                        }


                        Bc_high = "";
                        if (bchigh.Count ==6)
                        {
                            int sum = 0;
                            foreach (ResultEntry s in bchigh)
                            {
                                sum += s.ValueY;
                            }
                            Bc_high += sum / 6;
                        }




                        RaisePropertyChanged();
                        selectPureToneResultIsChange();
                    }
                }



            }
        }



        public void selectPureToneResultIsChange()
        {
            Left_ac = "pack://application:,,,/../Assets/Images/left_type_" + SelectPureToneResult.AcLeftType + ".png";
            Right_ac = "pack://application:,,,/../Assets/Images/right_type_" + SelectPureToneResult.AcRightType + ".png";
            Left_ac_mask = "pack://application:,,,/../Assets/Images/left_type_"+ SelectPureToneResult.AcLeftMaskedType+".png";
            Right_ac_mask = "pack://application:,,,/../Assets/Images/right_type_" + SelectPureToneResult.AcRightMaskedType + ".png";

            Left_bc = "pack://application:,,,/../Assets/Images/left_type_" + SelectPureToneResult.BcLeftType + ".png";
            Right_bc = "pack://application:,,,/../Assets/Images/right_type_" + SelectPureToneResult.BcRightType + ".png";
            Left_bc_mask = "pack://application:,,,/../Assets/Images/left_type_" + SelectPureToneResult.BcLeftMaskedType + ".png";
            Right_bc_mask = "pack://application:,,,/../Assets/Images/right_type_" + SelectPureToneResult.BcRightMaskedType + ".png";

            Left_ff = "pack://application:,,,/../Assets/Images/left_type_21.png";
            Right_ff = "pack://application:,,,/../Assets/Images/right_type_21.png";
            Left_ff_mask = "pack://application:,,,/../Assets/Images/left_type_23.png";
            Right_ff_mask = "pack://application:,,,/../Assets/Images/right_type_23.png";


            foreach (ResultDataSet dataset in SelectPureToneResult.DataSets)
            {
                Dictionary<int, TestItem> dict = new Dictionary<int, TestItem>();
                foreach (ResultEntry entry in dataset.Entrys)
                {
                    TestItem item = new TestItem();
                    item.Hz = entry.ValueX;
                    item.Db = entry.ValueY;
                    if (entry.PointState == 1)
                    {
                        item.Mask = true;
                        item.MaskV = 0;
                        //...
                    }
                    else
                    {
                        item.Mask = false;
                        item.MaskV = 0;
                        //...
                    }


                    if (entry.IsUserResp == 0)
                        item.IsUserResp = false;
                    else
                        item.IsUserResp = true;
                    item.MarkType = entry.MarkType;
                    item.abc = entry.Mmtype;
                    dict.Add(item.Hz, item);

                    //List<TestItem> listChild = this.rightResult.ToList();
                    //listChild.Sort(delegate (TestItem p1, TestItem p2) { return Comparer<int>.Default.Compare(p1.Hz, p2.Hz); });
                    ////List列表转为ObservableCollection集合
                    //this.rightResult = new ObservableCollection<TestItem>(listChild);
                }
                //this.IsRightEar 
                SelectPureToneResultEvent(dict, dataset.IsRight == 1, dataset.HeadsetMode, SelectPureToneResult.State);

            }
        }
        public MemberInfo SelectMember
        {
            get => selectMember;
            set
            {


                if (value != null)
                {
                    selectMember = value;
                }
                RaisePropertyChanged();

            }
        }

        public string TitleText { get => titleText; set { titleText = value; SaveTitleInfo(); RaisePropertyChanged(); } }

        public PreviewPageViewModel()
        {

            //AddMemberCommand = new RelayCommand(AddMember);
            //EditMemberCommand = new RelayCommand(EditMember);
            //DeleteMemberCommand = new RelayCommand(DeleteMember);
            //SearchMemberCommand = new RelayCommand(SearchMember);


            //db = new MemberInfoDb(dbconfig.DatabasePath);
            //userDB = new UserDb(dbconfig.DatabasePath);
            resultDB = new PureToneResultDb(dbconfig.DatabasePath);
            //dataSetDB = new ResultDataSetDb(dbconfig.DatabasePath);
            //entryDB = new ResultEntryDb(dbconfig.DatabasePath);
            //getInitInfo();

            //Task t1 = new Task(new Action(getInitInfo));
            //t1.Start();
            // getInitInfo();
            //DMSkin.Core.Broadcast.RegisterBroadcast<string>("NavigationBack", (obj) =>
            //{
            //    getInitInfo();
            //});
            //DMSkin.Core.Broadcast.RegisterBroadcast<string>("NavigationBack2", (obj) =>
            //{
            //    getInitInfo();
            //});

            ReadConfigTitleInfo();
        }

        public PreviewPageViewModel(PureToneResult result,MemberInfo member)
        {

        
            resultDB = new PureToneResultDb(dbconfig.DatabasePath);
            SelectMember = member;
            SelectPureToneResult = result;
    
        }

        public void ReadConfigTitleInfo()
        {
            var basePath = Environment.CurrentDirectory;

            string cfgINI = System.IO.Path.Combine(basePath, "title2.ini");

            if (File.Exists(cfgINI))
            {

                //FileStream wr= File.OpenRead(cfgINI);
                TitleText = File.ReadAllText(cfgINI, Encoding.UTF8);
                //IniFile ini = new IniFile(cfgINI);
                //TitleText = ini.IniReadValue("SET", "NAME");

                //  SkinName = ini.IniReadValue("Skin", "Skin");
                // ServerType = ini.IniReadValue("Server", "Bridge");
            }
            else
            {
                TitleText = "听力测试报告";
            }
        }

        public void SaveTitleInfo()
        {
            var basePath = Environment.CurrentDirectory;

            string cfgINI = System.IO.Path.Combine(basePath, "title2.ini");

            if (File.Exists(cfgINI))
            {
                File.Delete(cfgINI);
            }
            //IniFile ini = new IniFile(cfgINI);
            //ini.IniWriteValue("SET", "NAME", TitleText);
            File.WriteAllText(cfgINI, TitleText, Encoding.UTF8);

        }

    }
}
